package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.AdminUserDetailResponse;
import com.luo.backend.dto.AdminUserListResponse;
import com.luo.backend.dto.UpdateUserStatusRequest;
import com.luo.backend.entity.User;
import com.luo.backend.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 管理员-用户管理控制器
 */
@RestController
@RequestMapping("/api/v1/admin")
public class AdminUserController {
    
    @Autowired
    private AdminUserService adminUserService;
    
    /**
     * 获取管理员个人信息
     * GET /api/v1/admin/profile
     */
    @GetMapping("/profile")
    public ApiResponse<User> getAdminProfile(HttpServletRequest request) {
        User user = (User) request.getAttribute("user");
        return ApiResponse.success(user);
    }
    
    /**
     * 获取用户列表
     * GET /api/v1/admin/users
     */
    @GetMapping("/users")
    public ApiResponse<AdminUserListResponse> getUserList(
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String sortOrder) {
        
        AdminUserListResponse response = adminUserService.getUserList(
            page, size, keyword, role, status, sortBy, sortOrder
        );
        return ApiResponse.success(response);
    }
    
    /**
     * 获取用户详情
     * GET /api/v1/admin/users/{id}
     */
    @GetMapping("/users/{id}")
    public ApiResponse<AdminUserDetailResponse> getUserDetail(@PathVariable Long id) {
        AdminUserDetailResponse response = adminUserService.getUserDetail(id);
        return ApiResponse.success(response);
    }
    
    /**
     * 删除用户
     * DELETE /api/v1/admin/users/{id}
     */
    @DeleteMapping("/users/{id}")
    public ApiResponse<String> deleteUser(@PathVariable Long id) {
        adminUserService.deleteUser(id);
        return ApiResponse.success("删除成功");
    }
    
    /**
     * 更新用户状态（启用/禁用）
     * PUT /api/v1/admin/users/{id}/status
     */
    @PutMapping("/users/{id}/status")
    public ApiResponse<String> updateUserStatus(
            @PathVariable Long id,
            @Valid @RequestBody UpdateUserStatusRequest request) {
        
        adminUserService.updateUserStatus(id, request.getStatus());
        String message = request.getStatus() == 1 ? "启用成功" : "禁用成功";
        return ApiResponse.success(message);
    }
}

